package jwt

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"

	"go_api/pkg/e"
	"go_api/pkg/util"
)

func JWT() gin.HandlerFunc {
	return func(c *gin.Context) {
		var code int
		code = e.SUCCESS
		token := c.Request.Header.Get("Authorization")
		//token := c.Query("token")
		if token == "" {
			code = e.ERROR
		} else {
			token = strings.TrimPrefix(token, "Bearer ")
			_, err := util.ParseToken(token, c)
			if err != nil {
				switch err.(*jwt.ValidationError).Errors {
				case jwt.ValidationErrorExpired:
					code = e.ERROR
				default:
					code = e.ERROR
				}
			}
		}

		if code != e.SUCCESS {

			c.JSON(http.StatusUnauthorized, gin.H{
				"code": "error",
				"msg":  e.GetMsg(code),
			})
			c.Abort()
			return
		}

		c.Next()
	}
}
